package org.tim.websocket.chat;

import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.tim.es.message.UserPrivateMessage;
import org.tim.es.message.UserPrivateMessageResource;
import org.tim.common.msg.MsgType;
import org.tim.common.msg.TimMessage;
import org.tim.es.session.UserPrivareSessionResource;
import org.tio.core.ChannelContext;
import org.tio.websocket.common.WsResponse;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class PrivateReadChatKit implements BeforeChatKit {
    @Autowired
    private UserPrivateMessageResource privateMessageResource;

    @Autowired
    private UserPrivareSessionResource userPrivareSessionResource;

    @Override
    public boolean isSupport(TimMessage timMessage) {
        return MsgType.READ.equals(timMessage.getMsgType());
    }

    public void beforeChat(WsResponse wsResponse, TimMessage timMessage, ChannelContext channelContext, Promise<TimMessage> promise) {
        var id = timMessage.getId();

        synchronized (this) {
            if (Strings.isNotEmpty(id)) {
                if (timMessage.getDate() == null) {
                    timMessage.setDate(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
                }
                var now = Instant.ofEpochSecond(timMessage.getDate()).atOffset(ZoneOffset.of("+8")).toLocalDateTime();

                var optional = privateMessageResource.findById(timMessage.getId());
                if (optional.isPresent()) {
                    var message = optional.get();

                    var sessionId = message.getSessionId();
                    var sessionPresent = userPrivareSessionResource.findById(sessionId);
                    if (sessionPresent.isPresent()) {
                        var session = sessionPresent.get();

                        privateMessageResource.updateAllUnRead(sessionId, now);

                        userPrivareSessionResource.save(session.setUnreadCnt(0L));
                    }

                    message.setRead(Boolean.TRUE);
                    message.setReadAt(now);
                    privateMessageResource.save(message);
                } else {
                    promise.setFailure(new Throwable("Send read msg but msg empty"));
                }
            } else {
                promise.setFailure(new Throwable("Send read msg but msgId empty"));
            }
        }
    }
}
